package com.just.bz_back.interceoter;

import com.just.bz_back.config.CheckRole;
import com.just.bz_back.model.dto.JsonData;
import com.just.bz_back.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 * 拦截是否登录
 * @author:baibaiwuchang
 * @Data:2019/2/11 13:04
 */
@Slf4j
public class LoginInterceoter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String url=request.getRequestURI();
        String token=request.getHeader("token");
        if (token==null)
        {
            token=request.getParameter("token");
        }
        if (token!=null)
        {
            Claims claims= JwtUtil.checkJWT(token);
            if (claims !=null) {
                Integer id = (Integer) claims.get("id");
                String username=(String) claims.get("username");
                int roleGrade = (int) claims.get("role");
                request.setAttribute("user_id", id);
                log.info("---用户操作----用户{},操作接口{}",username,url);
                CheckRole checkRole = getCheckSource((HandlerMethod) handler);
                if (checkRole.roleId() >  roleGrade) {
                    SendMessage.sendJsonMessage(response, JsonData.buildError("权限不够",403));
                    return false;
                }
                return true;
            }
        }
        SendMessage.sendJsonMessage(response, JsonData.buildError("请登录",405));
        return false;
    }

    /**
     * 拿到该方法上的CheckRole注解对象
     */
    private CheckRole getCheckSource(HandlerMethod handlerMethod) {
        if (handlerMethod.getBeanType().isAnnotationPresent(CheckRole.class)) {
            return handlerMethod.getBeanType().getAnnotation(CheckRole.class);
        } else if (handlerMethod.getMethod().isAnnotationPresent(CheckRole.class)) {
            return handlerMethod.getMethod().getAnnotation(CheckRole.class);
        }
        return null;
    }
}
